<?php

namespace app\api\model;

use app\common\model\Language as LanguageModel;

class Language extends LanguageModel
{
    public function getBackgroundimageAttr($value)
    {
        return $value ? request()->domain().$value : '';
    }

    /**
     * 获取语种
     */
    public static function getLanguages()
    {
        return self::where(static::whereOnline())->order(static::WEIGH_DESC)->select();
    }

    /**
     * 首页语种
     */
    public static function getHomeLanguage($userId = 0)
    {
        $languages = self::getLanguages();
        if (!$languages) {
            static::error(998);
        }
        foreach ($languages as $val) {
            //需求id
            $needQuestionId = 0;
            if ($userId) {
                $needQuestion = NeedQuestion::getByUserId($val->language_id, $userId);
                $needQuestionId = $needQuestion ? $needQuestion->need_question_id : 0;
            }
            $val['need_question_id'] = $needQuestionId;
        }
        return $languages;
    }

    public function question()
    {
        return $this->belongsToMany(Question::class, 'language_quetion', 'language_id', 'question_id');
    }

    /**
     * 获取添加需求的语种
     */
    public static function getNeedLanguages($userId)
    {
        $languageId = NeedQuestion::getColumnByUserId($userId, 'language_id');
        return self::where(static::whereOnline())->whereNotIn('language_id', $languageId)->select();
    }

    public static function getBySearch($name)
    {
        $languageId = self::where('title', 'like', "%{$name}%")->column('language_id');
        return $languageId ?: [];
    }

}
